package edu.usm.roberge.orbitz;

import java.util.Map.Entry;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import edu.usm.roberge.HttpRequest;

/**
 * The second request in a sequence of 3
 * Mimics submitting the "find flights" form
 * The results of submitting this form is a "loading" page
 * Inside the HTML is a link that the page is forwarded to after a few
 * seconds delay which displays the results
 */
public class OrbitzSubmissionRequest {
	
	// regex to grab the url of the results page
	private final static Pattern RESULT_URL_REG_EX = Pattern.compile("<meta(?:.*?)url=([^\\\"]+)\"");

	// required form parameters to submit
	private final static String FLIGHT_TYPE_PARAM = "flightType";
	private final static String ORIGIN_PARAM = "origin";
	private final static String DESTINATION_PARAM = "destination";
	private final static String START_DATE_PARAM = "startDate";
	private final static String USE_START_CAL_PARAM = "useStartCal";
	private final static String START_TIME_PARAM = "startTime";
	private final static String END_DATE_PARAM = "endDate";
	private final static String USE_END_CAL_PARAM = "useEndCal";
	private final static String END_TIME_PARAM = "endTime";
	private final static String ADULTS_PARAM = "adults";
	private final static String SEARCH_PARAM = "Search.x";
	
	private final static String URL = "http://www.orbitz.com";
	private final HttpRequest request;
	private final OrbitzData data;

	public OrbitzSubmissionRequest(OrbitzData data) {
		this.data = data;
		request = new HttpRequest(URL + data.getSubmissionUrl());
	}
	
	public OrbitzData getResultData() {
		addParametersToRequest();
		String response = request.makeRequest();
		data.addCookies(request.getHeader("Set-Cookie"));
		processResponse(response);
		return data;
	}

	private void addParametersToRequest() {
		request.addRequestHeader("Cookie", data.getCookies()).setPostRequest();
		
		
		for(Entry<String, String> hiddenParam : data.getHiddenParams()) {
			request.addParameter(hiddenParam.getKey(), hiddenParam.getValue());
		}
		
		request.addParameter(FLIGHT_TYPE_PARAM, "roundtrip")
			   .addParameter(ORIGIN_PARAM, "bos")
			   .addParameter(DESTINATION_PARAM, "orlando")
			   .addParameter(START_DATE_PARAM, "11/10/11")
			   .addParameter(USE_START_CAL_PARAM, "true")
			   .addParameter(START_TIME_PARAM, "Anytime")
			   .addParameter(END_DATE_PARAM, "11/14/11")
			   .addParameter(USE_END_CAL_PARAM, "true")
			   .addParameter(END_TIME_PARAM, "Anytime")
			   .addParameter(ADULTS_PARAM, "1")
			   .addParameter(SEARCH_PARAM, "true");
	}
	
	private void processResponse(String response) {
		Matcher matcher = RESULT_URL_REG_EX.matcher(response);
		if (!matcher.find()) {
			// TODO: error page
		}
		
		data.setResultsUrl(matcher.group(1));
	}
}

